package com.hk.Mgr.web.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.order.PayRecordReq;
import com.hk.commons.utils.EncryptDecryptUtils;
import com.hk.app.utils.RedisCilent;
import com.hk.base.ResponseBase;
import com.hk.commons.CacheConstants;
import com.hk.commons.ConstantCard;
import com.hk.commons.ConstantOrderStatus;
import com.hk.commons.ConstantProduct;
import com.hk.commons.ConstantRoute;
import com.hk.commons.DateUtil;
import com.hk.commons.MapSortUtil;
import com.hk.commons.ResultCode;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.Card;
import com.hk.commons.entity.UserCard;
import com.hk.commons.entity.order.OrderInfo;
import com.hk.commons.entity.pay.FYBackPayRecord;
import com.hk.commons.entity.pay.PayRecord;
import com.hk.commons.entity.product.ProductInfo;
import com.hk.commons.entity.sys.ApiSecret;
import com.hk.commons.utils.sys.MD5Crypter;
import com.hk.service.IOrganization;
import com.hk.service.kyc.ICard;
import com.hk.service.kyc.IUserCard;
import com.hk.service.order.IFYBackPayRecord;
import com.hk.service.order.IOrderHandle;
import com.hk.service.order.IOrderInfo;
import com.hk.service.order.IPayRecord;
import com.hk.service.product.IProductInfo;
import com.hk.service.sys.IApiSecret;
import com.hk.service.sys.ISysUser;

@Controller
public class PaySecurityCtrl {

	private Logger logger = LoggerFactory.getLogger(PaySecurityCtrl.class);
	@Autowired
	private IApiSecret apiSecretService;

	@Value("${fy.Secret}")
	private String fySecret;

	@Value("${fy.mchntCd}")
	private String mchntCd;

	@Autowired
	private IPayRecord payRecordService;

	@Autowired
	private IOrderInfo orderInfoService;

	@Autowired
	private IProductInfo productService;

	@Autowired
	private IFYBackPayRecord fybacBackService;

	@Autowired
	private IOrderHandle<OrderInfo> hkOrderHandleImpl;

	@Autowired
	private IUserCard userCardService;

	@Autowired
	private ICard cardService;

	@Autowired
	private ISysUser sysUserService;

	@Autowired
	private IOrganization organizService;

	@Value("${hk.logsBaseUrl}")
	private String logsBaseUrl;

	/**
	 * 富友支付后富友的回调接口
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/fyPayBackValidate", method = RequestMethod.POST)
	public ResponseBase<String> payValidate(HttpServletRequest request) {
		// request.setCharacterEncoding("gbk");
		logger.info("进入富友回调函数");
		ResponseBase<String> base = new ResponseBase<String>();
		String version = request.getParameter("VERSION");
		String type = request.getParameter("TYPE");
		String responseCode = request.getParameter("RESPONSECODE");
		String responseMsg = request.getParameter("RESPONSEMSG");
		String mchntcd = request.getParameter("MCHNTCD");
		String mchntOrderId = request.getParameter("MCHNTORDERID");
		String orderId = request.getParameter("ORDERID");
		String amt = request.getParameter("AMT");
		String bankCard = request.getParameter("BANKCARD");
		String sign = request.getParameter("SIGN");
		logger.info(
				"入参为version={}，type={}，responseCode={}，responseMsg={}，mchntcd={}，mchntOrderId={}，orderId={}，amt={}，bankCard={}，sign={}",
				version, type, responseCode, responseMsg, mchntcd,
				mchntOrderId, orderId, amt, bankCard, sign);
		if (StringHelper.isEmpty(version) || StringHelper.isEmpty(type)
				|| StringHelper.isEmpty(responseCode)
				|| StringHelper.isEmpty(responseMsg)
				|| StringHelper.isEmpty(mchntcd)
				|| StringHelper.isEmpty(mchntOrderId)
				|| StringHelper.isEmpty(orderId) || StringHelper.isEmpty(amt)
				|| StringHelper.isEmpty(bankCard) || StringHelper.isEmpty(sign)) {
			logger.info("PaySecurityCtrl->fyPayBackValidate->入参有值为空！");
			base.setMsg("入参有值为空！");
			base.setResultCode(ResultCode.FAILED.getCode());
			base.setResult("入参有值为空！");
		} else {
			logger.info("PaySecurityCtrl->payValidate->url的sign为={}", sign);
			String allUrl = type + "|" + version + "|" + responseCode + "|"
					+ mchntcd + "|" + mchntOrderId + "|" + orderId + "|" + amt
					+ "|" + bankCard + "|" + fySecret;
			logger.info("PaySecurityCtrl->fyPayBackValidate->拼接的url={}", allUrl);

			String md5After2 = MD5Crypter.md5Encrypt(allUrl);
			logger.info("PaySecurityCtrl->fyPayBackValidate->md5加密后的sign={}",
					md5After2);
			if (md5After2.equals(sign)) {
				FYBackPayRecord fyBackPayRecord = new FYBackPayRecord();
				fyBackPayRecord.setAmt("" + Double.parseDouble(amt) / 100);// 富友返回分，转为元
				fyBackPayRecord.setBankCard(bankCard);
				fyBackPayRecord.setCts(System.currentTimeMillis());
				fyBackPayRecord.setMchntcd(mchntcd);
				fyBackPayRecord.setMchntOrderId(mchntOrderId);
				fyBackPayRecord.setOrderDate(DateUtil.transferLongToDate(
						"yyyyMMddHHmmss", System.currentTimeMillis()));
				fyBackPayRecord.setOrderId(orderId);
				fyBackPayRecord.setResponseCode(responseCode);
				fyBackPayRecord.setResponseMsg(responseMsg);
				fyBackPayRecord.setSign(sign);
				fyBackPayRecord.setType(type);
				fyBackPayRecord.setVersion(version);
				try {
					writeFyBackFile(fyBackPayRecord);

				} catch (Exception e) {
					logger.error("写富友回调订单文件失败！", e);
				}
				try {
					fybacBackService.add(fyBackPayRecord);
				} catch (Exception e) {
					logger.error("添加富友回调订单到库失败！", e);
				}
				if ("0000".equals(fyBackPayRecord.getResponseCode())) {
					try {
						String fyOrder = RedisCilent
								.getString(CacheConstants.FY_CREATE_ORDERINFO
										+ mchntOrderId);
						if (StringHelper.isNotEmpty(fyOrder)) {
							addToOrderInfo(fyOrder, fyBackPayRecord);
							RedisCilent
									.delKey(CacheConstants.FY_CREATE_ORDERINFO
											+ mchntOrderId);
						} else {
							logger.info("缓存中不存在需要创建的订单");
						}
					} catch (Exception e) {
						logger.error("更新订单确认表失败！", e);
					}
				}
				base.setMsg("成功");
				base.setResultCode(ResultCode.SUCC.getCode());
				base.setResult("成功");
			} else {
				logger.info("PaySecurityCtrl->payValidate->sign不一致");
				base.setMsg("sign不一致");
				base.setResultCode(ResultCode.FAILED.getCode());
				base.setResult("sign不一致");
			}
		}

		return base;
	}

	/**
	 * 添加订单信息
	 * 
	 * @param fyOrderInfo
	 * @param payRecord
	 */
	private void addToOrderInfo(String fyOrderInfo, FYBackPayRecord payRecord) {
		try {
			// 获取redis中预存的order信息
			JSONObject obj = new JSONObject(fyOrderInfo);
			Long id = (Long) obj.get("id");
			Long userId = (Long) obj.get("userId");
			String brokerOrderNo = obj.getString("brokerOrderNo");
			Long orderCreatedOn = (Long) obj.get("orderCreatedOn");
			int companyId = (Integer) obj.get("companyId");
			Long productId = (Long) obj.get("productId");
			int confirmStatus = (Integer) obj.get("confirmStatus");
			Long financialPlannerId = null;
			int channel = (Integer) obj.get("channel");

			if (obj.has("financialPlannerId")) {
				financialPlannerId = (Long) obj.get("financialPlannerId");
			}

			Long paymentId = (Long) obj.get("paymentId");
			OrderInfo orderInfo = new OrderInfo();
			orderInfo.setProductId(productId);
			orderInfo.setUserId(userId);
			orderInfo.setId(id);
			orderInfo.setCompanyId(companyId);
			orderInfo.setBrokerOrderNo(brokerOrderNo);
			orderInfo.setConfirmStatus(confirmStatus);
			orderInfo.setOrderCreatedOn(orderCreatedOn);
			orderInfo.setPaymentId(paymentId);
			orderInfo.setFinancialPlannerId(financialPlannerId);
			orderInfo.setChannel(channel);
			if (obj.has("orgId")) {
				int orgId = (Integer) obj.get("orgId");
				orderInfo.setOrgId(orgId);
			}
			BigDecimal amount = new BigDecimal(0);
			if (payRecord.getAmt() != null) {
				amount = new BigDecimal(payRecord.getAmt());
			}
			BigDecimal dividend = new BigDecimal(0);
			ProductInfo productInfo = productService.findById(productId);
			BigDecimal prodDividend = new BigDecimal(0);
			BigDecimal extraDividend = new BigDecimal(0);
			if (productInfo != null) {
				BigDecimal allRate = new BigDecimal("0");
				BigDecimal yearRate = new BigDecimal(productInfo
						.getMaxYearRate().replace("%", ""))
						.divide(new BigDecimal(100));
				allRate = allRate.add(yearRate);
				int days = productInfo.getProTerm();
				// 投资金额*年化收益率*30/360*(投资天数/30)

				// 获取加息券
				String userCardId = RedisCilent
						.getString(CacheConstants.FY_USERCARD_ORDERINFO + id);
				logger.info("orderId = {}, userCardId = {}", id, userCardId);
				if (StringHelper.isNotEmpty(userCardId)) {//
					UserCard userCard = userCardService.findById(Long
							.parseLong(userCardId));
					int Status = userCard.getStatus();
					Card card = cardService.findById(userCard.getCardId());
					BigDecimal rate = card.getRate();
					if (ConstantCard.CARD_STATUS_NO_ACTIVE == Status) {// 如果该加息券未使用，则使用它并更新状态
						allRate = allRate.add(rate);
						extraDividend = getExtraProfit(rate, amount, days);
						// 更新加息券状态
						userCardService.updateUserCardInfo(userCard,
								ConstantCard.CARD_STATUS_ACTIVE, id);
						orderInfo.setUserCardId(Long.parseLong(userCardId));
						RedisCilent.delKey(CacheConstants.FY_USERCARD_ORDERINFO// 删除加息券id
								+ id);
					} else {// 已使用，则看使用的是否为当前订单。
						Long cardOrderId = userCard.getOrderId();
						if (cardOrderId != null
								&& (cardOrderId.longValue() == id.longValue())) {
							allRate = allRate.add(rate);
							extraDividend = getExtraProfit(rate, amount, days);
							orderInfo.setUserCardId(Long.parseLong(userCardId));
							RedisCilent
									.delKey(CacheConstants.FY_USERCARD_ORDERINFO// 删除加息券id
											+ id);
						}
					}
				}
				extraDividend = extraDividend.setScale(2,
						BigDecimal.ROUND_HALF_UP);
				prodDividend = amount
						.multiply(yearRate)
						.multiply(new BigDecimal(days))
						.divide(new BigDecimal(365), 2,
								BigDecimal.ROUND_HALF_UP);// BigDecimal.ROUND_HALF_UP表示的就是4舍5入。
				dividend = amount
						.multiply(allRate)
						.multiply(new BigDecimal(days))
						.divide(new BigDecimal(365), 2,
								BigDecimal.ROUND_HALF_UP);
				orderInfo.setExtraDividend(extraDividend);
				orderInfo.setProdDividend(prodDividend);
				orderInfo.setDividend(dividend);
				Long orderCreateOn = orderInfo.getOrderCreatedOn();
				Calendar nowCalendar = Calendar.getInstance();
				nowCalendar.setTime(new Date(orderCreateOn));
				nowCalendar.add(Calendar.DAY_OF_MONTH, +1);// +1今天的时间加一天
				Calendar calendar = Calendar.getInstance();
				calendar.set(nowCalendar.get(Calendar.YEAR),
						nowCalendar.get(Calendar.MONTH),
						nowCalendar.get(Calendar.DAY_OF_MONTH), 0, 0, 1);
				Long orderTradeDates = calendar.getTime().getTime();
				calendar.add(Calendar.DAY_OF_YEAR, days);
				Long orderDividendDate = calendar.getTime().getTime();
				orderInfo.setOrderConfirmDate(orderTradeDates);
				orderInfo.setOrderTradeDate(orderTradeDates);
				orderInfo.setDividendDate(orderDividendDate);
				productService.updAmountByPay(productId, amount, true);

			} else {
				logger.info("查询不到该产品,productId={}", productId);
			}
			orderInfo.setOrderConfirmDate(System.currentTimeMillis());
			orderInfo.setPayStatus(ConstantOrderStatus.PAY_STATUS_TRUE);
			orderInfo
					.setConfirmStatus(ConstantOrderStatus.CONFIRM_STATUS__TRUE);
			orderInfo.setSuccessAmount(new BigDecimal(payRecord.getAmt()));

			// 如果是非自动起息,并且未开始计息
			if (productInfo.getAutStartDiv() == ConstantProduct.PRO_NO_AUTO_START_DIV
					&& (productInfo.getStartDiv() == ConstantProduct.PRO_NOT_START_DIV)) {
				orderInfo.setOrderTradeDate(null);
				orderInfo.setDividendDate(null);
				orderInfo.setOrderConfirmDate(null);
				orderInfo
						.setConfirmStatus(ConstantOrderStatus.CONFIRM_STATUS__NO_CONFIRM);
			}

			orderInfoService.add(orderInfo);
			// 如果订单生成成功，则创建订单路由信息
			hkOrderHandleImpl.createOrderRoute(userId, id,
					ConstantRoute.COMPANY_HUAKANG);
		} catch (Exception e) {
			logger.error("添加orderInfo订单异常！", e);
			// e.printStackTrace();
		}

	}

	private BigDecimal getExtraProfit(BigDecimal rate, BigDecimal amount,
			int days) {
		BigDecimal extraProfit = new BigDecimal(0);
		extraProfit = amount.multiply(rate).multiply(new BigDecimal(days))
				.divide(new BigDecimal(365), 5, BigDecimal.ROUND_HALF_UP);// 四舍五入
		// 使用加息券后单笔额外增加的利润最高为5000元，超过5000元仍按5000元发放；
		if (extraProfit.compareTo(new BigDecimal(5000)) == 1) {// 1是大于
			extraProfit = new BigDecimal(5000);
		}
		return extraProfit;
	}

	/**
	 * ios、android富友支付后内部校验接口
	 * 
	 * @param payRecord
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/payValidate", method = RequestMethod.POST)
	public ResponseBase<String> payValidate(@RequestBody PayRecordReq payRecord) {
		ResponseBase<String> base = new ResponseBase<String>();
		try {
			Map<String, String> map = getParamValue(payRecord);
			String responseCode = map.get("orderPayCode");
			if ("0000".equals(responseCode)) {
				if (checkToken(map.get("isIdempotent"), map.get("userId"))) {
					ApiSecret apiSecretObj = apiSecretService.findByApikey(map
							.get("apikey"));
					String apiSecret = apiSecretObj.getApiSecret();
					if (EncryptDecryptUtils.validateSignByMap(apiSecret, map)) {
						payHandle(payRecord);
						base.setMsg("成功");
						base.setResultCode(ResultCode.SUCC.getCode());
						base.setResult("订单支付成功");
					} else {
						logger.info(
								"PaySecurityCtrl--payValidate不匹配:入参sign={}",
								map.get("sign").toString());
						base.setMsg("sign不匹配");
						base.setResultCode(ResultCode.FAILED.getCode());
						base.setResult("订单支付失败");
					}
					logger.info(new JSONObject(base).toString());
				} else {
					logger.info("token校验失败！");
					base.setMsg("token校验失败！");
					base.setResultCode(ResultCode.FAILED.getCode());
					base.setResult("token校验失败！");
				}
			} else {
				base.setMsg("订单支付失败");
				base.setResultCode(ResultCode.FAILED.getCode());
				base.setResult("订单支付失败");
			}

		} catch (Exception e) {
			logger.error("PaySecurityCtrl--payHandle异常", e);
			base.setMsg("PaySecurityCtrl--payHandle异常");
			base.setResultCode(ResultCode.FAILED.getCode());
			base.setResult("订单支付失败");
			// e.printStackTrace();
		}

		return base;
	}

    @ResponseBody
    @RequestMapping(value = "/apiSecret", method = RequestMethod.GET)
    public ResponseBase<String> apiSecret(String apiKey) {
        ResponseBase<String> base = new ResponseBase<String>();
        try {
            if(StringUtils.isBlank(apiKey))
                throw new Exception("apiKey 不能为空");

            ApiSecret apiSecretObj = apiSecretService.findByApikey(apiKey);
            String apiSecret = apiSecretObj.getApiSecret();

            base.setMsg("成功");
            base.setResultCode(ResultCode.SUCC.getCode());
            base.setResult(apiSecret);
        } catch (Exception e) {
            logger.error(" get apiSecret异常", e);
            base.setMsg(e.getMessage());
            base.setResultCode(ResultCode.FAILED.getCode());
        }

        return base;
    }

	public boolean checkToken(String token, String userId) {
		if (StringHelper.isEmpty(userId)) {

			return false;
		}
		if (StringHelper.isEmpty(token)) {

			return false;
		}

		/* 不为空校验 */

		if (RedisCilent.existsKey(CacheConstants.VALIDATE_TOKEN + token)) {
			String redisUserId = RedisCilent
					.getString(CacheConstants.VALIDATE_TOKEN + token);
			if (StringHelper.isEmpty(redisUserId)) {

				return false;
			} else {
				if (!userId.equals(redisUserId)) {

					return false;
				} else {
					RedisCilent.delKey(CacheConstants.VALIDATE_TOKEN + token);
					return true;
				}
			}
		} else {

			return false;
		}
	}

	public void payHandle(PayRecordReq payRecord) {
		PayRecord payRecordEntityPay = new PayRecord();
		payRecordEntityPay.setCardNo(payRecord.getCardNo());
		if (!StringHelper.isEmpty(payRecord.getChannce())) {
			payRecordEntityPay.setChannce(Integer.parseInt(payRecord
					.getChannce()));
		}
		Long cts = System.currentTimeMillis();
		payRecordEntityPay.setCts(cts);

		payRecordEntityPay.setFailReason(payRecord.getFailReason());
		payRecordEntityPay.setFySSn(payRecord.getFySSn());
		// payRecordEntityPay.setId(payRecord.getId());
		payRecordEntityPay.setMchnt_cd(payRecord.getMchnt_cd());
		payRecordEntityPay.setMd5(payRecord.getMd5());
		payRecordEntityPay.setOrderAmount(Double.parseDouble(payRecord// 转为元
				.getOrderAmount()) / 100 + "");
		payRecordEntityPay.setOrderDate(DateUtil.transferLongToDate(
				"yyyyMMddHHmmss", cts));
		payRecordEntityPay.setOrderId(payRecord.getOrderId());
		payRecordEntityPay.setOrderPayCode(payRecord.getOrderPayCode());
		payRecordEntityPay.setOrderPayError(payRecord.getOrderPayError());
		payRecordEntityPay.setOrderStatus(payRecord.getOrderStatus());
		payRecordEntityPay.setUserId(payRecord.getUserId());
		try {
			writeFile(payRecordEntityPay);
		} catch (Exception e) {
			logger.error("写支付流水文件失败！", e);
			// e.printStackTrace();
		}
		try {
			payRecordService.add(payRecordEntityPay);
		} catch (Exception e) {
			logger.error("添加payRecord记录到表失败！", e);
			// e.printStackTrace();
		}
		// 避免富友回调延迟，而实际已经扣款的情况，此时则要先把加息券状态更改
		try {
			// 获取加息券
			String userCardId = RedisCilent
					.getString(CacheConstants.FY_USERCARD_ORDERINFO
							+ payRecord.getOrderId());
			if (StringHelper.isNotEmpty(userCardId)) {//
				UserCard userCard = userCardService.findById(Long
						.parseLong(userCardId));
				int Status = userCard.getStatus();
				if (ConstantCard.CARD_STATUS_NO_ACTIVE == Status) {// 如果该加息券未使用，则更新状态
					userCardService.updateUserCardInfo(userCard,
							ConstantCard.CARD_STATUS_ACTIVE,
							Long.valueOf(payRecord.getOrderId()));
					// RedisCilent.delKey(CacheConstants.FY_USERCARD_ORDERINFO//不能删除，当富友回调回来需要更新加息金额
					// 删除加息券id
					// + payRecord.getOrderId());
				}
			}
		} catch (Exception e) {
			logger.error("更新加息券状态失败！", e);
		}

	}

	public StringBuilder getFyPayRecordString(FYBackPayRecord payRecord) {
		StringBuilder payRecordStringBuilder = new StringBuilder();
		int fyPayCount = 0;
		try {
			fyPayCount = Integer.parseInt(RedisCilent
					.getString(CacheConstants.Pay_FYBACK_COUNT));
		} catch (Exception e) {
			logger.error("redis异常！", e);
		}

		fyPayCount++;
		payRecordStringBuilder.append(fyPayCount + "|" + payRecord.getAmt()
				+ "|" + payRecord.getBankCard() + "|" + payRecord.getMchntcd()
				+ "|" + payRecord.getMchntOrderId() + "|"
				+ payRecord.getOrderDate() + "|" + payRecord.getOrderId() + "|"
				+ payRecord.getResponseCode() + "|"
				+ payRecord.getResponseMsg() + "|" + payRecord.getSign() + "|"
				+ payRecord.getType() + "|" + payRecord.getVersion() + "|"
				+ payRecord.getCts() + "|" + "\r\n");
		RedisCilent.setString(CacheConstants.Pay_FYBACK_COUNT,
				String.valueOf(fyPayCount));
		return payRecordStringBuilder;
	}

	public StringBuilder getPayRecordString(PayRecord payRecord) {
		StringBuilder payRecordStringBuilder = new StringBuilder();
		int payCount = 0;
		try {
			payCount = Integer.parseInt(RedisCilent
					.getString(CacheConstants.Pay_SECURITY_COUNT));
		} catch (Exception e) {
			logger.error("redis异常！", e);
		}

		payCount++;
		payRecordStringBuilder.append(payCount + "|" + payRecord.getMchnt_cd()
				+ "|" + payRecord.getCardNo() + "|" + payRecord.getOrderId()
				+ "|" + payRecord.getOrderDate() + "|" + payRecord.getCts()
				+ "|" + payRecord.getOrderAmount() + "|"
				+ payRecord.getOrderStatus() + "|"
				+ payRecord.getOrderPayCode() + "|"
				+ payRecord.getOrderPayError() + "|" + payRecord.getResv1()
				+ "|" + payRecord.getFySSn() + "|" + payRecord.getMd5() + "|"
				+ payRecord.getUserId() + "|" + payRecord.getChannce() + "|"
				+ payRecord.getFailReason() + "\r\n");
		RedisCilent.setString(CacheConstants.Pay_SECURITY_COUNT,
				String.valueOf(payCount));
		return payRecordStringBuilder;
	}

	public void writeFile(PayRecord payRecord) {
		Long cts = System.currentTimeMillis();
		String pathName = "hkPayRecord-"
				+ DateUtil.transferLongToDate("yyyyMMdd", cts) + ".txt";
		Path filePath = Paths.get(logsBaseUrl + "/hkPayRecord/" + pathName);
		// Path filePath = Paths.get("D:\\testFile\\" + pathName);
		StringBuilder payRecordBuild = getPayRecordString(payRecord);
		if (!Files.exists(filePath)) {
			try {
				StringBuilder fileStr = new StringBuilder();
				fileStr.append("0 | | 1\r\n")
						.append("序号|商户代码 |卡号|订单号|订单日期|生成订单时间戳|交易金额(元)|订单状态|错误代码|错误中文描述|保留字段| 富友流水号|MD5摘要|用户ID|渠道|失败原因\r\n");
				fileStr.append(payRecordBuild);

				Files.write(filePath, fileStr.toString().getBytes("UTF-8"));
			} catch (IOException e) {
				logger.error("首次写文件失败！", e);
				// e.printStackTrace();
			}
		} else {// 存在则追加
			try {
				Files.write(filePath,
						payRecordBuild.toString().getBytes("UTF-8"),
						StandardOpenOption.APPEND);
			} catch (IOException e) {
				logger.error("追加写文件失败！", e);
				// e.printStackTrace();
			}

		}

	}

	public void writeFyBackFile(FYBackPayRecord payRecord) {
		Long cts = System.currentTimeMillis();
		String pathName = "hkFYPayRecord-"
				+ DateUtil.transferLongToDate("yyyyMMdd", cts) + ".txt";
		Path filePath = Paths.get(logsBaseUrl + "/hkFYPayRecord/" + pathName);
		// Path filePath = Paths.get("D:\\testFile\\" + pathName);
		StringBuilder payRecordBuild = getFyPayRecordString(payRecord);
		if (!Files.exists(filePath)) {
			try {
				StringBuilder fileStr = new StringBuilder();
				fileStr.append("序号|金额(元)|卡号|商户代码|请求订单号|订单日期|富友订单号|错误代码|错误中文描述|sign|交易类型|版本号|时间戳|\r\n");
				fileStr.append(payRecordBuild);

				Files.write(filePath, fileStr.toString().getBytes("UTF-8"));
			} catch (IOException e) {
				logger.error("首次写文件失败！", e);
				// e.printStackTrace();
			}
		} else {// 存在则追加
			try {
				Files.write(filePath,
						payRecordBuild.toString().getBytes("UTF-8"),
						StandardOpenOption.APPEND);
			} catch (IOException e) {
				logger.error("追加写文件失败！", e);
				// e.printStackTrace();
			}

		}

	}

	public Map<String, String> getParamValue(PayRecordReq payRecord) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("apiKey", payRecord.getApiKey());
		map.put("cardNo", payRecord.getCardNo());
		if (!StringHelper.isEmpty(payRecord.getChannce())) {
			map.put("channce", payRecord.getChannce());
		}
		// map.put("cts", payRecord.getCts());
		if (!StringHelper.isEmpty(payRecord.getFailReason())) {
			map.put("failReason", payRecord.getFailReason());
		}
		map.put("fySSn", payRecord.getFySSn());
		map.put("mchnt_cd", payRecord.getMchnt_cd());
		map.put("md5", payRecord.getMd5());
		map.put("orderAmount", payRecord.getOrderAmount());
		// map.put("orderDate", payRecord.getOrderDate());
		map.put("orderId", payRecord.getOrderId());
		map.put("orderPayCode", payRecord.getOrderPayCode());
		if (!StringHelper.isEmpty(payRecord.getOrderPayError())) {
			// map.put("orderPayError", payRecord.getOrderPayError());
			map.put("orderPayError",
					String.valueOf(payRecord.getOrderPayError().length()));
			// map.put("orderPayError",
			// chinaToUnicode(payRecord.getOrderPayError()));
		}
		map.put("orderStatus", payRecord.getOrderStatus());
		map.put("md5", payRecord.getMd5());
		map.put("sign", payRecord.getSign());
		map.put("isIdempotent", payRecord.getIsIdempotent());// token
		map.put("userId", payRecord.getUserId());
		map = MapSortUtil.sortMapByKey(map);
		return map;
	}

}
